import React, { Component } from 'react';
import _ from 'lodash';
import {
  StyleSheet, View, Text, TouchableOpacity, Modal, FlatList,
  TouchableWithoutFeedback, ScrollView,
} from 'react-native';
import produce from 'immer';
import { Icon } from 'native-base';
import ZlstIcon from './zlst-icons';
import {
  ListFooter, BlankBackground, Loading,
} from './index';
import * as todoService from '../services/todo';
import MySearchBar from './searchbar';
import theme from '../native-base-theme/variables';
import MyHeader from './header';

export default class FormSelect extends Component {
  page = 1; // 分页请求的当前页数

  startPosition = 0; // 开始滑动的位置

  index = 0; // 记录当前page的index

  searchValue = '';

  constructor(props) {
    super(props);
    this.state = {
      list: [],
      refreshing: false,
      isMore: false,
      isError: false,
      showLoading: true,
    };
  }

  componentDidMount() {
    this._onInitRefresh();
  }

  fetchList = async (payload) => {
    try {
      this.setState({ isError: false });
      const currPage = this.page + 1;
      const { list, page, total } = await todoService.choiceSearch({ ...payload, page: currPage }, this.props.searchUri);

      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list.push(...list);
        this.page = page;
        draft.isMore = draft.list.length < total;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true });
    }
  }

  refreshList = async (payload) => {
    try {
      this.setState({ isError: false });
      const { list, page, total } = await todoService.choiceSearch({ ...payload, page: 1 }, this.props.searchUri);
      const isMore = list.length < total;
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list = list;
        draft.refreshing = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
    }
  }

  initRefreshList = async (payload) => {
    try {
      this.setState({ showLoading: true, isError: false, list: [] });
      const { list, page, total } = await todoService.choiceSearch({ ...payload, page: 1 }, this.props.searchUri);
      const isMore = list.length < total;
      this.setState(produce(draft => {
        draft.list = list;
        draft.showLoading = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, showLoading: false });
    }
  }

  // 刷新时候获取数据
  _onRefresh = () => {
    this.refreshList({ condition: this.searchValue });
  }

  // 初始化的时候获取数据
  _onInitRefresh = () => {
    this.initRefreshList({ condition: this.searchValue });
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.fetchList({ condition: this.searchValue });
    }
  }

  _onItemClick = (item, index) => {
    this.state.list.forEach(ele => {
      ele.checked = false;
    });
    this.state.list[index].checked = true;
    const { list } = this.state;
    this.setState({
      list,
    });
  }

  // 列表的item组件
  _renderItem = (item) => {
    console.log(item);
    return (
      <TouchableOpacity
        style={[styles.listItem, { backgroundColor: item.item.checked ? '#207aff' : theme.myPrimary }]}
        onPress={() => this._onItemClick(item)}
      >
        <Text style={{ color: 'white', marginTop: 5, marginBottom: 5 }}>
          {`${item.splitCode} ${item.materialName}`}
        </Text>
      </TouchableOpacity>
    );
  };

  _getListContent = () => {
    const { list } = this.state;
    const doms = [];
    for (let i = 0, len = list.length; i < len; i += 1) {
      const item = list[i];
      doms.push(
        <TouchableOpacity
          style={[styles.listItem, { backgroundColor: item.checked ? '#207aff' : theme.myPrimary }]}
          onPress={() => this._onItemClick(item, i)}
          key={i}
        >
          <Text style={{ color: 'white', marginTop: 5, marginBottom: 5 }}>
            {`${item.splitCode} ${item.materialName}`}
          </Text>
        </TouchableOpacity>,
      );
    }
    return doms;
  }

  // 列表的分割线
  _renderItemSeparator = () => (
    <View style={{ height: 0.5, backgroundColor: '#EDF5FA' }} />
  )

  // 列表上拉加载的组件
  _renderListFooter = () => (
    <ListFooter isMore={false} />
  );

  _onSearch = async (searchValue) => {
    this.searchValue = searchValue;
    this.initRefreshList({ condition: this.searchValue });
  }

  choiceConfirm = () => {
    const list = this.state.list.filter((it) => (it.checked));
    if (list && list.length > 0) {
      this.props.choiceConfirm(list);
      this.props.onClose();
    } else {
      alert('请至少选择一个');
    }
  };

  modalBackHandler = () => {
    this.choiceConfirm();
  }

  render() {
    const { list, show } = this.props;
    if (!this.state.list.length) {
      this.state.list = list;
    }
    const header = (
      <View
        style={{
          backgroundColor: theme.myPrimary,
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          paddingTop: 10,
          paddingBottom: 10,
        }}
      >
        <TouchableWithoutFeedback onPress={this.modalBackHandler}>
          <View style={{ padding: 5 }}>
            <ZlstIcon
              style={styles.backIcon}
              name="fanhui"
              size={20}
              color="#ffffff"
            />
          </View>
        </TouchableWithoutFeedback>
        <Text style={{ fontSize: 18, fontWeight: 'bold', color: '#ffffff' }}>请选择备件</Text>
        <View style={styles.rightOperate} />
      </View>
    );

    return (
      <Modal
        visible={show}
        animationType="none"
        transparent={false}
        onRequestClose={this.modalBackHandler}
        style={styles.modalConteniner}
      >
        {header}
        <View style={{ flex: 1, backgroundColor: theme.myPrimary }}>
          <ScrollView>
            {this._getListContent()}
          </ScrollView>
        </View>
        <TouchableOpacity style={styles.footer} onPress={this.choiceConfirm} activeOpacity={0.8}>
          <Text style={{ color: 'white' }}>确定</Text>
        </TouchableOpacity>
        {/* {!this.props.searchNoHeader && (
          <TouchableOpacity style={styles.footer} onPress={this.choiceConfirm} activeOpacity={0.8}>
            <Text style={{ color: 'white' }}>确定</Text>
          </TouchableOpacity>
        )} */}
      </Modal>
    );
  }
}

const styles = StyleSheet.create({
  modalConteniner: {
    flex: 1,
    height: 200,

  },
  record_text: {
    paddingLeft: 10,
    paddingBottom: 10,
    fontSize: 12,
  },
  record_text_container: {
    padding: 10,
    flex: 1,
  },
  record_text_bg: {
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: '#DEE1E6',
    backgroundColor: '#fff',
  },
  clear_text_bg: {
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: '#DEE1E6',
    textAlign: 'center',
    fontSize: 12,
  },
  footer: {
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: theme.myPrimary,
    height: 48,
    borderTopWidth: 0.5,
    borderTopColor: 'rgba(255,255,255,0.5)',
  },
  listItem: {
    padding: 10,
    justifyContent: 'space-between',
    flexDirection: 'row',
  },
});
